package com.qf.timer;

import com.event.util.EventUtil;
import com.qf.entity.Goods;
import com.qf.entity.Msg;
import com.qf.feign.GoodsFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * 定时任务 1 55分
 */
@Component
public class TimeTask {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsFeign goodsFeign;

    @Autowired
    private EventUtil eventUtil;

    /**
     * 整数小时
     */
    @Scheduled(cron = "0 55 1/2 * * *")
    public void handler(){
        System.out.println("午时已到!" + new Date());

        //获得当前的时间字符串
        Integer timeScore = Integer.parseInt(new SimpleDateFormat("yyMMddHHmm").format(new Date()));

        //根据时间串，获取需要提醒的消息信息
        Set<String> infoSet = redisTemplate.opsForZSet().rangeByScore("tixing_zset", timeScore, timeScore);

        //循环处理
        infoSet.stream().forEach(s -> {
            // uid_gid
            Integer uid = Integer.parseInt(s.split("_")[0]);
            Integer gid = Integer.parseInt(s.split("_")[1]);

            //查询商品信息
            Goods goods = goodsFeign.getGoodById(gid).getData();

            //设置推送的消息
            Msg msg = new Msg()
                    .setTo(uid)
                    .setType(2)
                    .setData(goods.getSubject());

            //通过事件总线广播给消息中心
            eventUtil.sendMsg("tixing", msg);
        });
    }
}
